﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using ThoughtWorks.QRCode.Codec;
using System.Windows.Forms;


namespace QR_Code
{
    /// <summary>
    /// function：web页面输入一段文字，定向生成二维码，复杂二维码生成请看【QR_Encode_Decode】
    /// </summary>
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("生成成功！", "小提示", 
                                 MessageBoxButtons.OKCancel,
                                 MessageBoxIcon.Question,
                                 MessageBoxDefaultButton.Button2,
                                 0,
                                 "单机确定按钮生成二维码") == DialogResult.OK)
            {
                CreateQRImg(this.TextBox1.Text);
                MessageBox.Show("快去E:\\test\\testMethod\\QR_Code\\photos查看二维码吧！");
            }
            else 
            {
                CYMessageBox.Show("生成失败","错误提示",
                                   CYMessageBox.CYButtons.OKCancel,
                                   CYMessageBox.CYIcon.Warning);//仿MessageBox重绘方法
            }
        }
        /// <summary>
        /// 生成并保存二维码图片的方法
        /// </summary>
        /// <param name="str">输入的内容</param>
        private void CreateQRImg(string str)
        {
            Bitmap bt;
            string enCodeString = str;
            //生成设置编码实例
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置二维码的规模，默认4
            qrCodeEncoder.QRCodeScale = 4;
            //设置二维码的版本，默认7
            qrCodeEncoder.QRCodeVersion = 7;
            //设置错误校验级别，默认中等
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //生成二维码图片
            bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
            //二维码图片的名称
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
            //保存二维码图片在photos路径下
            bt.Save(Server.MapPath("~/photos/") + filename + ".jpg");
            //图片控件要显示的二维码图片路径
            this.Image1.ImageUrl = "~/photos/" + filename + ".jpg";
        }
    }
}